package basic;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class MessageDAOJpa {

	public static void main(String[] args) {
		// Start EntityManagerFactory
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("messagepu");

		// 插入
		EntityManager em = emf.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();

		Message message = new Message("Hello World with JPA");
		em.persist(message);

		tx.commit();
		em.close();

		// 查询
		EntityManager newEm = emf.createEntityManager();
		EntityTransaction newTx = newEm.getTransaction();
		newTx.begin();

		List messages = newEm.createQuery("select m from Message m order by m.text asc")
				.getResultList();

		System.out.println(messages.size() + " message(s) found:");

		for (Object m : messages) {
			Message loadedMsg = (Message) m;
			System.out.println(loadedMsg.getId());
			System.out.println(loadedMsg.getText());
		}

		newTx.commit();
		newEm.close();

		// Shutting down the application
		emf.close();
	}
}
